package com.itheima.health.config;

import com.itheima.health.Security.SecurityUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configurers.provisioning.InMemoryUserDetailsManagerConfigurer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class Test02WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private SecurityUserDetails securityUserDetails;

    @Override
    public void configure(HttpSecurity http)throws Exception{
        //指定访问规则
        //通过authorizeRequests开启一个拦截规则
        //需要通过antMatchers拦截的资源，hasAnyAuthority指定哪些角色或者拥有哪些权限的人可以通过
        http.authorizeRequests().antMatchers("*.js","*.css").permitAll()
                .antMatchers("/pages/checkitem.html").hasAnyAuthority("add","ROLE_ADMIN","ROLE_OMS")
                .antMatchers("/pages/checkgroup.html").hasAnyAuthority("find","ROLE_ADMIN")
                .antMatchers("/main.html","/pages/**").authenticated();
        //配置登录相关内容
        http.formLogin().loginPage("/login.html")//登录成功跳转的页面
                .loginProcessingUrl("/sec/login")//登录请求地址
                .failureUrl("/login-fail.html")//登录失败跳转的地址
                .defaultSuccessUrl("/main.html");//登录成功跳转的地址
        //如果使用我们自己定义的页面，需要关闭防止csrf的攻击验证，否则我们的页面需要加入对应的复杂逻辑
        http.csrf().disable();

        //配置登出的相关内容
        http.logout().logoutUrl("/sec/logout")//配置登出的接口
                .logoutSuccessUrl("/login.html")//配置登出之后跳转的页面
                .invalidateHttpSession(true);//登出之后销毁session

        //配置权限不足时跳转的页面
        http.exceptionHandling().accessDeniedPage("/auth-fail.html");
    }

        @Override
    public void configure(AuthenticationManagerBuilder auth)throws Exception{
        //设置自定义的UserDetailService
        //auth.userDetailsService(?) ?传入userDetailsService本身或者是其子类
        auth.userDetailsService(securityUserDetails);
    }

}
